package com.payment.system.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.payment.common.base.AjaxResult;
import com.payment.common.support.Convert;
import com.payment.common.type.PaymentOrderType;
import com.payment.common.utils.DateUtils;
import com.payment.common.utils.Md5Utils;
import com.payment.common.utils.RedisPoolUtil;
import com.payment.common.utils.StringUtils;
import com.payment.common.utils.pay.EncryptUtil;
import com.payment.system.domain.*;
import com.payment.system.mapper.*;
import com.payment.system.service.IPlanNewService;
import com.payment.system.vo.CreditCardVo;
import com.payment.system.vo.PlanAcqVo;

import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 新计划 服务层实现
 *
 * @author payment
 * @date 2019-07-02
 */
@Service
public class PlanNewServiceImpl implements IPlanNewService {
    private static final Logger log = LoggerFactory.getLogger(PlanNewServiceImpl.class);
    @Autowired
    private PlanNewMapper planNewMapper;
    @Autowired
    private SystemConfigMapper configMapper;
    @Autowired
    private MerchantIncreaseLimitMapper merchantIncreaseLimitMapper;
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private AcqBindMapper acqBindMapper;
    @Autowired
    private PlanItemNewMapper planItemNewMapper;

    @Autowired
    private PaymentOrderMapper paymentOrderMapper;

    /**
     * 查询新计划信息
     *
     * @param id 新计划ID
     * @return 新计划信息
     */
    @Override
    public PlanNew selectPlanNewById(String id) {
        return planNewMapper.selectPlanNewById(id);
    }

    /**
     * 查询新计划列表
     *
     * @param planNew 新计划信息
     * @return 新计划集合
     */
    @Override
    public List<PlanNew> selectPlanNewList(PlanNew planNew) {
        List<PlanNew> list = planNewMapper.selectPlanNewList(planNew);
        for (PlanNew planNew1 : list) {
            // 敏感信息脱敏
            planNew1.setCardNumberA(EncryptUtil.desEncryptMessage(planNew1.getCardNumberA()));
            planNew1.setCardNumberB(EncryptUtil.desEncryptMessage(planNew1.getCardNumberB()));
        }
        return list;
    }

    /**
     * 查询新计划列表 不加密
     *
     * @param planNew 新计划信息
     * @return 新计划集合
     */
    @Override
    public List<PlanNew> selectPlanNewListNoEncrypt(PlanNew planNew) {
        return planNewMapper.selectPlanNewList(planNew);
    }

    /**
     * 新增新计划
     *
     * @param planNew 新计划信息
     * @return 结果
     */
    @Override
    public int insertPlanNew(PlanNew planNew) {
        return planNewMapper.insertPlanNew(planNew);
    }

    /**
     * 修改新计划
     *
     * @param planNew 新计划信息
     * @return 结果
     */
    @Override
    public int updatePlanNew(PlanNew planNew) {
        return planNewMapper.updatePlanNew(planNew);
    }

    /**
     * 删除新计划对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deletePlanNewByIds(String ids) {
        return planNewMapper.deletePlanNewByIds(Convert.toStrArray(ids));
    }

    /**
     * app删除计划
     */
    @Override
    public AjaxResult deletePlan(String planId, String payPwd) {
        if (StringUtils.isEmpty(planId) || StringUtils.isEmpty(payPwd)) {
            return AjaxResult.error(1, "缺失必要参数");
        }

        PlanNew pl = planNewMapper.selectPlanNewById(planId);
        if (pl == null) {
            return AjaxResult.error(1, "获取计划信息失败");
        }
        if (pl.getStatus() == 2 || pl.getStatus() == 4) {
            return AjaxResult.error(2, "计划执行中或执行异常的禁止删除，如有疑问请咨询客服");
        }
        Merchant mer = merchantMapper.selectMerchantById(pl.getMerchantId());
        if (!mer.getPaymentPwd().equals(Md5Utils.encrypt2MD5(payPwd))) {
            return AjaxResult.error(4, "支付密码输入不正确");
        }

        PlanNew planNewNow = new PlanNew();
        planNewNow.setId(pl.getId());
        if (pl.getStatus() == 0) {
            planNewNow.setStatus(5);
            planNewMapper.updatePlanNew(planNewNow);
            return AjaxResult.success("删除计划成功");
            // 执行中
        } else if (pl.getStatus() == 1) {
            List<PlanItemNew> planItemNewList = planItemNewMapper.selectPlanNewListByPlanIdAndStatus(planId, 3);
            if (planItemNewList != null && planItemNewList.size() > 0) {
                if (StringUtils.equals(planItemNewList.get(0).getMoneyType(), "payment")) {
                    planNewNow.setStatus(5);
                    planNewMapper.updatePlanNew(planNewNow);
                    return AjaxResult.success("删除计划成功");
                } else {
                    return AjaxResult.error(5, "执行中的计划不能删除");
                }
            } else {
                return AjaxResult.error(2, "执行中的计划不能删除");
            }
        } else if (pl.getStatus() == 3) {
            return AjaxResult.error(3, "计划已执行完成，无需再进行删除");
        } else if (pl.getStatus() == 5) {
            return AjaxResult.error(4, "计划已删除，无需再进行删除");
        } else {
            return AjaxResult.error(5, "未知计划状态禁止删除，如有疑问请咨询客服");
        }

    }

    /**
     * 根据卡号获取APP计划列表
     */

    @Override
    public AjaxResult getAppPlanList(String cardNumber, int pageIndex, Integer pageSize, Integer type) {
        // TODO Auto-generated method stub
        List<PlanNew> pl = planNewMapper.selectPlanListByCardNumberLimit(cardNumber, pageIndex, pageSize, type);
        List<PlanNew> newPl = new ArrayList<PlanNew>();
        for (PlanNew planNew : pl) {
            BigDecimal rate = new BigDecimal(planNew.getRate()).divide(BigDecimal.valueOf(100), 4, BigDecimal.ROUND_UP);
            System.out.println("费率：" + rate);
            BigDecimal rateMoney = planNew.getPlanAmt().multiply(rate).setScale(2, BigDecimal.ROUND_UP);
            BigDecimal proMoney = new BigDecimal(planNew.getPro())
                    .multiply(BigDecimal.valueOf(planNew.getMaxGroupNum())).setScale(2, BigDecimal.ROUND_UP);
            System.out.println("笔数：" + planNew.getMaxGroupNum() + "】笔数费：" + proMoney);
            planNew.setRateMoney(rateMoney.add(proMoney));
            newPl.add(planNew);
        }
        return AjaxResult.successAndData("成功", newPl);
    }

    /**
     * 生成预览计划
     *
     * @param carIdA      A卡id
     * @param carIdB      B卡id
     * @param cardNumberA A卡卡号
     * @param cardNumberB B卡卡号
     * @param cardNameA   A卡银行名称
     * @param cardNameB   B卡银行名称
     * @param planMoeny   还款金额
     * @param dateStr     还款时间数组
     * @param region      落地地区
     * @param merid       商户id
     * @param planType    还款类型 1智能(大小并行额) 2完美还 3智能（小额） 4智能（大额）
     * @param everyNum    每天还款笔数
     * @param acqListJson 通道列表
     * @return
     * @throws ParseException
     */
    @Override
    public AjaxResult createPlanEntrance(String carIdA, String carIdB, String cardNumberA, String cardNumberB,
                                         String cardNameA, String cardNameB, BigDecimal planMoeny, String dateStr, String region, String merid,
                                         Integer planType, Integer everyNum, String acqListJson, String merchantName, String merchantPhone)
            throws ParseException {
        String rateStr = "";
        try {
            rateStr = RedisPoolUtil.get("rate");
        } catch (Exception e) {
            rateStr = "nil";
        }
        if (rateStr == null || "".equals(rateStr) || "nil".equals(rateStr)) {
            SystemConfig config = configMapper.selectSystemConfigByConfigCode("rate");
            try {
                RedisPoolUtil.setex("rate", config.getConfigValue(), 86400);
            } catch (Exception e) {
                // TODO: handle exception
            }
            rateStr = config.getConfigValue();
        }
        /*** 获取光谷通道限制信息配置开始 **/
        String ggLimit = "";
        try {
            ggLimit = RedisPoolUtil.get("ggLimit");
        } catch (Exception e) {
            // TODO: handle exception
            ggLimit = "nil";
        }
        if (ggLimit == null || "nil".equals(ggLimit)) {
            SystemConfig config = configMapper.selectSystemConfigByConfigCode("ggLimit");
            RedisPoolUtil.setex("ggLimit", config.getConfigValue(), 86400);
            ggLimit = config.getConfigValue();
        }
        JSONObject gglimit = JSONObject.parseObject(ggLimit);
        /*** 获取光谷通道限制信息配置结束 **/
        // 时间串分割成数组
        String[] dates = dateStr.split(",");
        if (dates.length == 0) {
            return AjaxResult.error("时间格式错误");
        }
        // 费率配置转json对象
        JSONObject rateJson = JSONObject.parseObject(rateStr);
        // 笔数费
        BigDecimal pro = BigDecimal.ZERO;
        // 费率
        BigDecimal rate = BigDecimal.ZERO;

        BigDecimal vipPro = BigDecimal.ZERO;
        BigDecimal vipRate = BigDecimal.ZERO;
        // 1智能2完美还 获取费率
        if (planType.equals(1)) {
            pro = new BigDecimal(rateJson.getString("yk").split("\\+")[1]);
            rate = new BigDecimal(rateJson.getString("yk").split("\\+")[0]);
            vipPro = new BigDecimal(rateJson.getString("vipYk").split("\\+")[1]);
            vipRate = new BigDecimal(rateJson.getString("vipYk").split("\\+")[0]);
        } else if (planType.equals(2)) {
            pro = new BigDecimal(rateJson.getString("zyk").split("\\+")[1]);
            rate = new BigDecimal(rateJson.getString("zyk").split("\\+")[0]);
            vipPro = new BigDecimal(rateJson.getString("vipYk").split("\\+")[1]);
            vipRate = new BigDecimal(rateJson.getString("vipYk").split("\\+")[0]);
        } else if (planType.equals(3)) {
            pro = new BigDecimal(rateJson.getString("xyk").split("\\+")[1]);
            rate = new BigDecimal(rateJson.getString("xyk").split("\\+")[0]);
            vipPro = new BigDecimal(rateJson.getString("vipYk").split("\\+")[1]);
            vipRate = new BigDecimal(rateJson.getString("vipYk").split("\\+")[0]);
        } else if (planType.equals(4)) {
            pro = new BigDecimal(rateJson.getString("dyk").split("\\+")[1]);
            rate = new BigDecimal(rateJson.getString("dyk").split("\\+")[0]);
            vipPro = new BigDecimal(rateJson.getString("vipYk").split("\\+")[1]);
            vipRate = new BigDecimal(rateJson.getString("vipYk").split("\\+")[0]);
        }
        if (pro.compareTo(BigDecimal.ZERO) < 1 || rate.compareTo(BigDecimal.ZERO) < 1) {
            return AjaxResult.error(2, "获取费率失败");
        }
        // 计划详情列表
        List<Map<String, Object>> outList = new ArrayList<Map<String, Object>>();
        // 共还款几笔
        int length = dates.length * everyNum;
        if (length < 2) {
            return AjaxResult.error(6, "还款笔数最少为两笔");
        }
        // 总手续费
        BigDecimal toalFree = new BigDecimal("0");
        // 平均每笔应还的钱
        BigDecimal initialMoney = planMoeny.divide(new BigDecimal(length), 2, BigDecimal.ROUND_DOWN);
        // 每次要还的钱
        BigDecimal everyMoney = initialMoney;
        // 计划时间
        Map<String, Object> dayMap = new HashMap<String, Object>(16);
        // 组数
        int groupNum = 1;
        // 笔数费
        BigDecimal pensFree = pro.multiply(new BigDecimal(length));
        // 还剩多少钱没还
        BigDecimal blance = planMoeny;
        // 零碎还款金额
        BigDecimal smallMoney = BigDecimal.ZERO;
        // 还款金额list
        List<BigDecimal> paymentList = new ArrayList<>();
        // 取得通道列表下标
        int acqIndex = 0;
        /* 信用卡选择 */
        int cardIdex = 0;
        String cardId = "";
        String cardName = "";
        String cardNumber = "";
        BigDecimal everyMoney1 = BigDecimal.ZERO;
        if (planType.equals(2)) {
            everyNum = everyNum * 2;
            pensFree = pensFree.multiply(new BigDecimal(2));
        }
        // 循环天数
        for (int i = 0; i < dates.length; i++) {
            ArrayList<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            String startTime = dates[i];
            // 循环每天的还款次数
            for (int x = 1; x <= everyNum; x++) {
                List<PlanAcqVo> acqList = isSupport(region, acqListJson, gglimit);
                PlanAcqVo acq = new PlanAcqVo();
                /* 计算每次要还的金额 */
                if (i == dates.length - 1 && (x == everyNum || (planType.equals(2) && x == everyNum / 2))) {
                    // 最后一次把最后的手续费计算出来
                    BigDecimal aa = new BigDecimal(1).subtract(rate);
                    everyMoney = blance.divide(aa, 0, BigDecimal.ROUND_UP).add(pro).add(new BigDecimal(1));
                } else if (i == 0 && x == 0) {
                    // 第一次多消费一点
                    everyMoney = initialMoney.multiply(new BigDecimal(1.1)).setScale(0, BigDecimal.ROUND_UP);
                } else {
                    // 其他次数随机
                    BigDecimal ramDou = new BigDecimal(nextDouble(0.95, 1.1, 2)).setScale(2, BigDecimal.ROUND_DOWN);
                    everyMoney = initialMoney.multiply(ramDou).setScale(0, BigDecimal.ROUND_UP);
                }
                if (planType.equals(2) && x % 2 == 0) {
                    everyMoney = everyMoney1;
                } else {
                    everyMoney1 = everyMoney;
                }
                // 每回合的手续费
                BigDecimal everyFee = new BigDecimal(0);
                // 一回合的剩余金额
                BigDecimal rest = everyMoney;
                /* 最低最高消费限制 */
                if (everyMoney.compareTo(new BigDecimal("200")) < 1) {
                    return AjaxResult.error(1, "单笔还款金额需大于 200元,请更改还款时间或者调整金额");
                }
                if (planType.equals(1)) {
                    if (everyMoney.multiply(new BigDecimal(everyNum)).compareTo(new BigDecimal("20000")) >= 1) {
                        return AjaxResult.error(1, "每天还款金额需小于20000元,请更改还款时间或者调整金额");
                    }

                } else if (planType.equals(2)) {
                    if (everyMoney.multiply(new BigDecimal(everyNum)).compareTo(new BigDecimal("20000")) >= 1) {
                        return AjaxResult.error(1, "每天还款金额需小于20000元,请更改还款时间或者调整金额");
                    }
                } else if (planType.equals(4)) {
                    if (everyMoney.multiply(new BigDecimal(everyNum)).compareTo(new BigDecimal("20000")) >= 1) {
                        return AjaxResult.error(1, "每天还款金额需小于20000元,请更改还款时间或者调整金额");
                    }
                }
                // 银行单笔最高消费
                BigDecimal bankQuota = new BigDecimal(0);
                // 获取银行限额集合
                SystemConfig yxDayConfig = configMapper.selectSystemConfigByConfigCode("yxDay");
                JSONObject yxDay = JSONObject.parseObject(yxDayConfig.getConfigValue());
                MerchantIncreaseLimit merchantIncreaseLimit = merchantIncreaseLimitMapper
                        .selectByBankAccount(cardNumberA);
                for (PlanAcqVo acq3 : acqList) {
                    JSONObject acqConfig = yxDay.getJSONObject(acq3.getAcqCode());
                    if (acqConfig != null) {
                        if (StringUtils.isNotNull(merchantIncreaseLimit)) {
                            bankQuota = acqConfig.getBigDecimal(merchantIncreaseLimit.getBankName());
                            if (bankQuota != null) {
                                if (everyMoney.multiply(new BigDecimal(everyNum)).compareTo(bankQuota) >= 1) {
                                    return AjaxResult.error(1,
                                            "【" + cardNameA + "】每天还款金额需小于" + bankQuota + "元,请更改还款时间或者调整金额");
                                }
                            }
                        }
                    }
                }
                if (planType.equals("2")) {
                    MerchantIncreaseLimit merchantIncreaseLimitB = merchantIncreaseLimitMapper
                            .selectByBankAccount(cardNumberB);
                    for (PlanAcqVo acq3 : acqList) {
                        JSONObject acqConfig = yxDay.getJSONObject(acq3.getAcqCode());
                        if (acqConfig != null) {
                            if (StringUtils.isNotNull(merchantIncreaseLimitB)) {
                                bankQuota = acqConfig.getBigDecimal(merchantIncreaseLimitB.getBankName());
                                if (bankQuota != null) {
                                    if (everyMoney.multiply(new BigDecimal(everyNum)).compareTo(bankQuota) >= 1) {
                                        return AjaxResult.error(1,
                                                "【" + cardNameB + "】每天还款金额需小于" + bankQuota + "元,请更改还款时间或者调整金额");
                                    }
                                }
                            }
                        }
                        // 1001 七个银行限额
                        if (("1001").equals(acq3.getAcqCode()) && everyMoney.compareTo(BigDecimal.valueOf(5000)) >= 0) {
                            SystemConfig sysConfig = configMapper.selectSystemConfigByConfigCode("bankCode");
                            if (StringUtils.isNotNull(sysConfig)) {
                                if (sysConfig.getConfigValue().indexOf(merchantIncreaseLimitB.getBankName()) != -1) {
                                    return AjaxResult.error("单笔消费金额需小于5000元 ,请更改还款时间或者调整金额");
                                }
                            }
                        }
                    }
                }
                // 消费笔数
                int consumerNum = 2;
                double restMin = 0.4;
                double restMax = 0.6;
                double max = 0.6;
                int isSmall = 1;
                // everyNum.equals(2) ||
                /*
                 * if (initialMoney.compareTo(new BigDecimal("300")) < 1) { //
                 * 单笔还金额在200元以下消费一笔还一笔 consumerNum = 1; max = 1; } else if
                 * (initialMoney.compareTo(new BigDecimal("1800")) < 1) { //
                 * 每天还款两笔或者单笔还金额在1800元以下消费两笔还一笔 consumerNum = 2; restMin = 0.45;
                 * restMax = 0.5; max = 0.55; } else { // 单笔还金额在1800元以上消费三笔还一笔
                 * consumerNum = 3; restMin = 0.3; restMax = 0.35; max = 0.4; }
                 */
                List<PlanAcqVo> removeList = new ArrayList<>();
                /* 如果是完美还并且本次还款可能有消费金额大于1000的去除小额通道 */
                if (planType.equals(2) && rest.multiply(new BigDecimal(max)).compareTo(new BigDecimal(1000)) >= 0) {
                    for (PlanAcqVo acq2 : acqList) {
                        if (acq2.getIsSmall().equals(1)) {
                            removeList.add(acq2);
                        }
                    }
                    acqList.removeAll(removeList);
                }
                if (acqList == null || acqList.size() < 1) {
                    return AjaxResult.error(8, "您所开通的通道可能不支持该地区或该额度，请开通其他通道");
                }
                /* 顺序获取通道 */
                if (acqIndex < acqList.size()) {
                    acq = acqList.get(acqIndex);
                    acqIndex = acqIndex + 1;
                } else {
                    acq = acqList.get(0);
                    acqIndex = 0;
                }
                if (cardIdex == 0) {
                    cardId = carIdA;
                    cardName = cardNameA;
                    cardNumber = cardNumberA;
                    cardIdex = cardIdex + 1;
                } else {
                    cardId = carIdB;
                    cardName = cardNameB;
                    cardNumber = cardNumberB;
                    cardIdex = 0;
                }
                for (int j = 0; j < consumerNum; j++) {
                    Map<String, Object> map = new HashMap<String, Object>(16);
                    if (j == consumerNum - 1) { // 是否是最后一次
                        if (rest.compareTo(new BigDecimal(1000)) == 1) {
                            if (planType.equals(3)) {
                                return AjaxResult.error(1, "单笔消费金额需小于1000元,请更改还款时间或者调整金额");
                            } else if (planType.equals(1)) {
                                isSmall = 0;
                            }
                        }
                        // 计算单笔手续费
                        everyFee = everyFee.add(rest.multiply(rate).setScale(2, BigDecimal.ROUND_UP));
                        map.put("money", rest);
                        map.put("type", "sale");
                        map.put("status", "0");
                        map.put("cardId", cardId);
                        map.put("cardName", cardName);
                        map.put("cardNum", cardNumber);
                        map.put("groupNum", groupNum);
                        map.put("acqId", acq.getId());
                        map.put("acqCode", acq.getAcqCode());
                        map.put("region", region);
                        list.add(map);
                        // 还款
                        Map<String, Object> payMap = new HashMap<String, Object>(16);
                        // 计算手续费
                        BigDecimal payFee = everyFee.add(pro);
                        toalFree = toalFree.add(payFee);
                        // 计算出来的应还金额 直接删除多余的小数位，如2.35会变成2.3
                        BigDecimal toMoney = everyMoney.subtract(payFee).setScale(2, BigDecimal.ROUND_DOWN);
                        paymentList.add(toMoney);
                        if (i == dates.length - 1 && x == everyNum) {
                            payMap.put("money", toMoney.add(smallMoney));
                            payMap.put("type", "payment");
                            payMap.put("status", "0");
                            if (cardNumber.equals(cardNumberA)) {
                                payMap.put("cardName", cardNameB);
                                payMap.put("cardNum", cardNumberB);
                                payMap.put("cardId", carIdB);
                                if (planType.equals(1) || planType.equals(3) || planType.equals(4)) {
                                    blance = blance.subtract(toMoney);
                                }
                            } else {
                                payMap.put("cardName", cardNameA);
                                payMap.put("cardNum", cardNumberA);
                                payMap.put("cardId", carIdA);
                                if (planType.equals(2)) {
                                    blance = blance.subtract(toMoney);
                                }
                            }
                            payMap.put("groupNum", groupNum);
                            payMap.put("acqId", acq.getId());
                            payMap.put("acqCode", acq.getAcqCode());
                            payMap.put("region", region);
                            list.add(payMap);
                        } else {
                            // 不是最后一笔还款把零碎金额去掉先放大一百倍升级成分单位的
                            BigDecimal actualMoney = toMoney.multiply(new BigDecimal(100)).setScale(0,
                                    BigDecimal.ROUND_DOWN);
                            /** 计算实际还款金额 和 减去的零碎金额累加 */
                            String actualToMoney = actualMoney.toString();
                            String actualToMoney1 = actualToMoney.substring(0, actualToMoney.length() - 2);
                            String actualToMoney2 = actualToMoney.substring(actualToMoney1.length(),
                                    actualToMoney.length());
                            if (!planType.equals(2) && acqList.size() == 1
                                    && gglimit.getString("wallet").indexOf(acq.getAcqCode()) == -1) {
                                // 零碎金额累计超过一元还一次
                                BigDecimal tomoeny1 = BigDecimal.ZERO;
                                smallMoney = smallMoney
                                        .add(new BigDecimal(actualToMoney2).divide(new BigDecimal("100")).setScale(2));
                                tomoeny1 = new BigDecimal(actualToMoney1).setScale(0, BigDecimal.ROUND_DOWN);
                                if (smallMoney.compareTo(BigDecimal.ONE) >= 0) {
                                    actualToMoney = smallMoney.multiply(new BigDecimal(100))
                                            .setScale(0, BigDecimal.ROUND_DOWN).toString();
                                    actualToMoney1 = actualToMoney.substring(0, actualToMoney.length() - 2);
                                    actualToMoney2 = actualToMoney.substring(actualToMoney1.length(),
                                            actualToMoney.length());
                                    tomoeny1 = tomoeny1
                                            .add(new BigDecimal(actualToMoney1).setScale(0, BigDecimal.ROUND_DOWN));
                                    smallMoney = smallMoney.subtract(
                                            new BigDecimal(actualToMoney1).setScale(0, BigDecimal.ROUND_DOWN));
                                }
                                payMap.put("money", tomoeny1);
                            } else {
                                payMap.put("money", toMoney);
                            }
                            payMap.put("type", "payment");
                            payMap.put("status", "0");
                            if (cardNumber.equals(cardNumberA)) {
                                payMap.put("cardName", cardNameB);
                                payMap.put("cardNum", cardNumberB);
                                payMap.put("cardId", carIdB);
                                if (planType.equals(1) || planType.equals(3) || planType.equals(4)) {
                                    blance = blance.subtract(toMoney);
                                }
                            } else {
                                payMap.put("cardName", cardNameA);
                                payMap.put("cardNum", cardNumberA);
                                payMap.put("cardId", carIdA);
                                if (planType.equals(2)) {
                                    blance = blance.subtract(toMoney);
                                }
                            }
                            payMap.put("groupNum", groupNum);
                            payMap.put("acqId", acq.getId());
                            payMap.put("acqCode", acq.getAcqCode());
                            payMap.put("region", region);
                            list.add(payMap);
                        }
                        if (planType.equals(1)) {
                            if (isSmall == 0) {
                                for (PlanAcqVo acq2 : acqList) {
                                    if (acq2.getIsSmall().equals(1)) {
                                        removeList.add(acq2);
                                    }
                                }
                                acqList.removeAll(removeList);
                                if (acqList == null || acqList.size() < 1) {
                                    return AjaxResult.error(8, "您所开通的通道可能不支持该地区或该额度，请开通其他通道");
                                }
                            } else {
                                for (PlanAcqVo acq2 : acqList) {
                                    if (acq2.getIsSmall().equals(0)) {
                                        removeList.add(acq2);
                                    }
                                }
                                if (removeList.size() < acqList.size()) {
                                    acqList.removeAll(removeList);
                                }
                            }
                            acq = acqList.get(0);
                            for (Map<String, Object> map2 : list) {
                                if (map2.get("groupNum").equals(groupNum)) {
                                    map2.put("acqId", acq.getId());
                                    map2.put("acqCode", acq.getAcqCode());
                                }
                            }
                        }
                    } else {
                        try {
                            Double restDouble = nextDouble(restMin, restMax, 2);
                            // 本次消费金额
                            BigDecimal money = everyMoney.multiply(new BigDecimal(restDouble.toString())).setScale(0,
                                    BigDecimal.ROUND_DOWN);
                            rest = rest.subtract(money).setScale(0, BigDecimal.ROUND_DOWN);
                            everyFee = everyFee.add(money.multiply(rate).setScale(2, BigDecimal.ROUND_UP));// 计算单笔手续费
                            if (money.compareTo(new BigDecimal(1000)) == 1) {
                                if (planType.equals(3)) {
                                    return AjaxResult.error(1, "单笔消费金额需小于1000元,请更改还款时间或者调整金额");
                                } else if (planType.equals(1)) {
                                    isSmall = 0;
                                }
                            } else {
                                isSmall = 1;
                            }
                            map.put("money", money);
                            map.put("type", "sale");
                            map.put("status", "0");
                            map.put("cardId", cardId);
                            map.put("cardName", cardName);
                            map.put("cardNum", cardNumber);
                            map.put("groupNum", groupNum);
                            map.put("acqId", acq.getId());
                            map.put("acqCode", acq.getAcqCode());
                            map.put("region", region);
                            list.add(map);
                        } catch (Exception e) {
                            log.error("生成计划失败,请重新生成" + e.getMessage());
                            e.printStackTrace();
                            return AjaxResult.error(4, "生成计划失败,请重新生成");
                        }
                    }
                }
                groupNum++;
            }
            dayMap.put(startTime, list);
        }
        // 生成还款时间
        outList = planTimeCreate(dates, dayMap, outList);
        // 计算预留资金
        String turnOver = Collections.max(paymentList).add(toalFree).setScale(0, BigDecimal.ROUND_UP).toString();
        toalFree = toalFree.setScale(2, BigDecimal.ROUND_UP);
        BigDecimal vipToalFree = planMoeny.multiply(vipRate);
        BigDecimal vipProFree = vipPro.multiply(BigDecimal.valueOf(length));
        vipToalFree = vipToalFree.add(vipProFree).setScale(2, BigDecimal.ROUND_DOWN);
        Map<String, Object> retrunMap = new HashMap<>(16);
        // 节省多少
        retrunMap.put("vipFree", toalFree.subtract(vipToalFree));
        // 所需预留金
        retrunMap.put("turnOver", turnOver);
        // 总手续费
        retrunMap.put("toalFree", toalFree.toString());
        // 消费手续费
        retrunMap.put("free", toalFree.subtract(pensFree).toString());
        // 笔数费
        retrunMap.put("pensFree", pensFree.toString());
        // 计划详情
        retrunMap.put("dataList", outList);
        // 费率
        BigDecimal ra = rate.multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_DOWN);
        retrunMap.put("rate", ra.toString());
        // 笔数费
        retrunMap.put("pro", pro.setScale(2, BigDecimal.ROUND_DOWN));
        // 还款金额
        retrunMap.put("planMoney", planMoeny.toString());
        // 还款笔数
        retrunMap.put("everyNum", everyNum.toString());
        // 最大还款笔数
        retrunMap.put("maxGroupNum", groupNum);
        return AjaxResult.successAndData("成功", retrunMap);
    }

    private List<PlanAcqVo> isSupport(String region, String acqListJson, JSONObject gglimit) {
        List<PlanAcqVo> acqList = JSONArray.parseArray(acqListJson, PlanAcqVo.class);
        List<PlanAcqVo> romveList = new ArrayList<>();
        for (PlanAcqVo acq : acqList) {
            if (gglimit.getString("region_acqCode").indexOf(acq.getAcqCode()) != -1) {
                if (gglimit.getString(acq.getAcqCode() + "region").indexOf(region) != -1) {
                    // 限制地区包含客户选择地区
                    romveList.add(acq);
                }
            }
        }
        acqList.removeAll(romveList);
        return acqList;
    }

    @Override
    public AjaxResult createQuanEPlan(String carId, String cardNumber, String cardName, BigDecimal planMoeny,
                                      String dateStr, String region, String merId, Integer everyNum, String acqListJson, String merchantName,
                                      String merchantPhone) {
        List<PaymentOrder> orderList=paymentOrderMapper.selectPaymentOrderListByOrderType(merId,Convert.toIntArray("6,61"));
        if (orderList.size()<=0) {
            return AjaxResult.error(1, "您当前不能使用该功能，如有疑问请咨询客服工作人员！");
        }

        String rateStr = "";
        try {
            rateStr = RedisPoolUtil.get("rate");
        } catch (Exception e) {
            rateStr = "nil";
        }
        if (rateStr == null || "".equals(rateStr) || "nil".equals(rateStr)) {
            SystemConfig config = configMapper.selectSystemConfigByConfigCode("rate");
            try {
                RedisPoolUtil.setex("rate", config.getConfigValue(), 86400);
            } catch (Exception e) {
                // TODO: handle exception
            }
            rateStr = config.getConfigValue();
        }
        List<PlanAcqVo> acqList = JSONArray.parseArray(acqListJson, PlanAcqVo.class);
        if (acqList == null || acqList.size() == 0) {
            return AjaxResult.error("暂无还款渠道");
        }
        PlanAcqVo acq = acqList.get(0);
        // 时间串分割成数组
        String[] dates = dateStr.split(",");
        if (dates.length == 0) {
            return AjaxResult.error("时间格式错误");
        }
        // 费率配置转json对象
        JSONObject rateJson = JSONObject.parseObject(rateStr);
        // 笔数费
        BigDecimal pro = new BigDecimal(rateJson.getString("qy").split("\\+")[1]);
        // 费率
        BigDecimal rate = new BigDecimal(rateJson.getString("qy").split("\\+")[0]);
        if (pro.compareTo(BigDecimal.ZERO) < 1 || rate.compareTo(BigDecimal.ZERO) < 1) {
            return AjaxResult.error(2, "获取费率失败");
        }
        // 计划详情列表
        List<Map<String, Object>> outList = new ArrayList<Map<String, Object>>();
        // 共还款几笔
        int length = dates.length * everyNum;
        if (length < 2) {
            return AjaxResult.error(6, "还款笔数最少为两笔");
        }
        // 手续费
        BigDecimal rateFree = planMoeny.multiply(rate).setScale(2, BigDecimal.ROUND_UP);
        // 笔数费
        BigDecimal pensFree = pro.multiply(new BigDecimal(length));
        BigDecimal aa = BigDecimal.ONE.subtract(rate);
        // 应消手续费
        BigDecimal toalFree = rateFree.add(pensFree).divide(aa, 2, BigDecimal.ROUND_UP);
        // 平均每笔应还的钱
        BigDecimal initialMoney = planMoeny.divide(new BigDecimal(length), 2, BigDecimal.ROUND_DOWN);
        // 每回合要还的钱
        BigDecimal everyMoney = initialMoney;
        // 计划时间
        Map<String, Object> dayMap = new HashMap<String, Object>(16);
        // 组数
        int groupNum = 1;
        // 还剩多少钱没还
        BigDecimal blance = planMoeny;
        // 循环天数
        for (int i = 0; i < dates.length; i++) {
            ArrayList<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            String startTime = dates[i];
            // 循环每天的还款次数
            for (int x = 0; x < everyNum; x++) {
                if (i == dates.length - 1 && x == everyNum - 1) {
                    // 最后一次把剩余的还上
                    everyMoney = blance;
                } else if (i == 0 && x == 0) {
                    // 手续费
                    Map<String, Object> map = new HashMap<String, Object>(16);
                    map.put("status", "0");
                    map.put("cardId", carId);
                    map.put("cardName", cardName);
                    map.put("cardNum", cardNumber);
                    map.put("acqId", acq.getId());
                    map.put("acqCode", acq.getAcqCode());
                    map.put("region", region);
                    map.put("money", toalFree);
                    map.put("groupNum", 0);
                    map.put("type", "saleRate");
                    list.add(map);
                    everyMoney = initialMoney.setScale(0, BigDecimal.ROUND_UP);
                } else {
                    // 其他次数随机
                    BigDecimal ramDou = new BigDecimal(nextDouble(0.95, 1.1, 2)).setScale(2, BigDecimal.ROUND_DOWN);
                    everyMoney = initialMoney.multiply(ramDou).setScale(0, BigDecimal.ROUND_UP);
                }
                /* 最低最高消费限制 */
                if (everyMoney.compareTo(new BigDecimal("150")) < 1) {
                    return AjaxResult.error(1, "单笔还款金额需大于 150元,请更改还款时间或者调整金额");
                }
                if (everyMoney.compareTo(new BigDecimal("500")) == 1) {
                    return AjaxResult.error(1, "单笔还款金额需小于500元,请更改还款时间或者调整金额");
                }
                Map<String, Object> map = new HashMap<String, Object>(16);
                map.put("status", "0");
                map.put("cardId", carId);
                map.put("cardName", cardName);
                map.put("cardNum", cardNumber);
                map.put("acqId", acq.getId());
                map.put("acqCode", acq.getAcqCode());
                map.put("region", region);
                map.put("groupNum", groupNum);
                map.put("money", everyMoney.add(BigDecimal.ONE));
                map.put("type", "payment");
                list.add(map);
                blance = blance.subtract(everyMoney);
                Map<String, Object> map1 = new HashMap<String, Object>(16);
                map1.put("status", "0");
                map1.put("cardId", carId);
                map1.put("cardName", cardName);
                map1.put("cardNum", cardNumber);
                map1.put("acqId", acq.getId());
                map1.put("acqCode", acq.getAcqCode());
                map1.put("region", region);
                map1.put("groupNum", groupNum);
                map1.put("money", everyMoney);
                map1.put("type", "sale");
                list.add(map1);
                groupNum++;
            }
            dayMap.put(startTime, list);
        }
        // 生成还款时间
        outList = planTimeCreateQuanE(dates, dayMap, outList);
        Map<String, Object> retrunMap = new HashMap<>(16);
        // 所需预留金
        retrunMap.put("turnOver", toalFree);
        // 总手续费
        retrunMap.put("toalFree", toalFree.toString());
        // 消费手续费
        retrunMap.put("free", toalFree.subtract(pensFree).toString());
        // 笔数费
        retrunMap.put("pensFree", pensFree.toString());
        // 计划详情
        retrunMap.put("dataList", outList);
        // 费率
        BigDecimal ra = rate.multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_DOWN);
        retrunMap.put("rate", ra.toString());
        // 笔数费
        retrunMap.put("pro", pro.setScale(2, BigDecimal.ROUND_DOWN));
        // 还款金额
        retrunMap.put("planMoney", planMoeny.toString());
        // 还款笔数
        retrunMap.put("everyNum", everyNum.toString());
        // 最大还款笔数
        retrunMap.put("maxGroupNum", groupNum);
        return AjaxResult.successAndData("成功", retrunMap);
    }

    private List<Map<String, Object>> planTimeCreateQuanE(String[] dates, Map<String, Object> dayMap,
                                                          List<Map<String, Object>> outList) {
        // TODO Auto-generated method stub
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int k = 0; k < dates.length; k++) {
            String startTime = dates[k];
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> list = (List<Map<String, Object>>) dayMap.get(startTime);
            Calendar startCal = Calendar.getInstance();
            String[] starts = startTime.split("-");
            // 还款从 9点开始
            startCal.set(Integer.parseInt(starts[0]), Integer.parseInt(starts[1]) - 1, Integer.parseInt(starts[2]), 9,
                    0, 0);
            Calendar endcal = Calendar.getInstance();// 初始化一个时间操作对象
            for (int i = 0; i < list.size(); i++) {
                Map<String, Object> map = list.get(i);
                endcal.setTime(startCal.getTime());// 把开始时间赋值给结束时间
                endcal.add(Calendar.MINUTE, 30);
                Date time = DateUtils.randomDate(startCal.getTime().getTime(), endcal.getTime().getTime());// 获取一个随机时间
                // 把时间添加进list
                System.out.println(dateFormat.format(time));
                map.put("time", dateFormat.format(time));
                outList.add(map);
                endcal.add(Calendar.MINUTE, 30);
                startCal.setTime(endcal.getTime());
            }
        }
        return outList;
    }

    private List<Map<String, Object>> planTimeCreate(String[] dates, Map<String, Object> dayMap,
                                                     List<Map<String, Object>> outList) {
        // TODO Auto-generated method stub
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int k = 0; k < dates.length; k++) {
            String startTime = dates[k];
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> list = (List<Map<String, Object>>) dayMap.get(startTime);
            Calendar startCal = Calendar.getInstance();
            String[] starts = startTime.split("-");
            // 还款从 9点开始
            startCal.set(Integer.parseInt(starts[0]), Integer.parseInt(starts[1]) - 1, Integer.parseInt(starts[2]), 9,
                    0, 0);
            Calendar endcal = Calendar.getInstance();// 初始化一个时间操作对象
            for (int i = 0; i < list.size(); i++) {
                Map<String, Object> map = list.get(i);
                endcal.setTime(startCal.getTime());// 把开始时间赋值给结束时间
                if (list.get(i).get("type").equals("payment")) {
                    // 还款时间随机时间区间
                    // 一消一还 15:30-16:30
                    // 二消一还 15:30-16:30
                    // 三消一还 16:00-17:00
                    // 二消二还 12:00-13:00 16:30-17:30
                    endcal.add(Calendar.MINUTE, 60);
                } else {
                    if (list.size() == 2) {
                        // 一消一还 9-15 6个小时
                        endcal.add(Calendar.MINUTE, 360);
                    } else if (list.size() == 3) {
                        // 二消一还 9-12 13-15 2个小时
                        endcal.add(Calendar.MINUTE, 120);
                    } else if (list.size() == 4) {
                        // 三消一还 9-10:30 11:30-13:00 14:00-15:30
                        endcal.add(Calendar.MINUTE, 90);
                    } else {
                        // 二消二还 9-9:30 10:30-11:00
                        // 13:30-14:00 15:00-15:30
                        endcal.add(Calendar.MINUTE, 30);
                    }
                }
                Date time = DateUtils.randomDate(startCal.getTime().getTime(), endcal.getTime().getTime());// 获取一个随机时间
                // 把时间添加进list
                map.put("time", dateFormat.format(time));
                outList.add(map);
                if (list.get(i).get("type").equals("payment")) {
                    endcal.add(Calendar.MINUTE, 30);
                } else {
                    endcal.add(Calendar.MINUTE, 60);
                }
                startCal.setTime(endcal.getTime());
            }
        }
        return outList;
    }

    /**
     * 生成小数随机数
     *
     * @param x        开始
     * @param y        结束
     * @param accuracy 几位小数
     * @return
     */
    static double nextDouble(Double x, Double y, int accuracy) {
        if (x.doubleValue() == y.doubleValue()) {
            return x;
        }
        double d = x + Math.random() * y % (y - x);
        return new BigDecimal(d).setScale(accuracy, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    @Override
    public AjaxResult getPlanAcqList(String cardId, String cardNumber, String type, String bankCode) {
        List<PlanNew> pl = planNewMapper.selectBadDebt(cardNumber);
        if (pl.size() > 0) {
            return AjaxResult.error("该银行卡有未处理计划，请处理或联系客服");
        } else {
            List<PlanAcqVo> acqList = acqBindMapper.selectPlanAcqListByCardId(cardId, type);
            List<PlanAcqVo> romveList = new ArrayList<PlanAcqVo>();
            for (PlanAcqVo acq : acqList) {
                if (!StringUtils.isEmpty(acq.getSupportBankcode())) {
                    String[] support = acq.getSupportBankcode().split(",");
                    if (support != null && !ArrayUtils.contains(support, bankCode)) {
                        romveList.add(acq);
                    }
                }
                if (!StringUtils.isEmpty(acq.getNoSupportBankcode())) {
                    String[] noSuppor = acq.getNoSupportBankcode().split(",");
                    if (noSuppor != null && ArrayUtils.contains(noSuppor, bankCode)) {
                        romveList.add(acq);
                    }
                }
            }
            acqList.removeAll(romveList);
            if (acqList.size() > 0) {
                return AjaxResult.successAndData("成功", acqList);
            } else {
                return AjaxResult.error(2, "该卡暂无通道,如已全部开通即为没有支持该卡的通道");
            }
        }
    }

    @Override
    public AjaxResult getCardList(String acqIds, String merchantId, String userId, String cardId) {
        // TODO Auto-generated method stub

        if (StringUtils.isEmpty(merchantId)) {
            return AjaxResult.error(1, "获取信用卡信息列表：缺失参数");
        }
        List<CreditCardVo> list = null;
        if (acqIds == null || "".equals(acqIds)) {
            list = merchantIncreaseLimitMapper.selectCreditCardVoByMerchantId(merchantId);
        } else {
            String[] acqids = acqIds.split(",");
            list = merchantIncreaseLimitMapper.selectCreditCardVoByMerchantIdAndAcqIds(merchantId, acqids, cardId);
        }
        if (list != null) {
            for (CreditCardVo cardVo : list) {
                cardVo.setBankBackgroundImg(cardVo.getBankBackgroundImg());
                cardVo.setBankLogoImg(cardVo.getBankLogoImg());
                if (cardVo.getBillDay() != null && cardVo.getRepaymentDay() != null) {
                    /* 获取7天前的时间 */
                    Calendar calendar = Calendar.getInstance();
                    int day = calendar.get(Calendar.DAY_OF_MONTH); // 获取今天是几号
                    int repaymentDay = Integer.parseInt(cardVo.getRepaymentDay()); // 还款日
                    int billDay = Integer.parseInt(cardVo.getBillDay()); // 账单日
                    if (billDay > day) {
                        // 计算账单还有几天。 还款已还
                        cardVo.setCountDown("出账倒计时：" + (billDay - day) + "天");
                    } else {
                        // 已出账计算还款剩余天数
                        if (repaymentDay > day) {
                            cardVo.setCountDown("还款倒计时：" + (repaymentDay - day) + "天");
                        } else if (repaymentDay == day) {
                            cardVo.setCountDown("今日是还款最后一天");
                        } else {
                            Calendar calendar1 = Calendar.getInstance();
                            calendar1.set(Calendar.DATE, repaymentDay);
                            calendar1.add(Calendar.MONTH, 1);
                            long timec = calendar1.getTime().getTime() - DateUtils.getNowDate().getTime();
                            BigDecimal dayc = BigDecimal.valueOf(timec).divide(BigDecimal.valueOf(86400000), 0,
                                    BigDecimal.ROUND_DOWN);
                            cardVo.setCountDown("还款倒计时：" + dayc + "天");
                        }
                    }
                } else {
                    cardVo.setCountDown("获取还款日与账单日失败");
                }
                if (StringUtils.isEmpty(cardVo.getIdCardNumber())) {
                    Merchant merchant = merchantMapper.selectMerchantById(merchantId);
                    if (merchant != null) {
                        cardVo.setIdCardNumber(merchant.getIdCardNumber());
                        MerchantIncreaseLimit merchantIncreaseLimit = merchantIncreaseLimitMapper
                                .selectMerchantIncreaseLimitById(cardVo.getId());
                        merchantIncreaseLimit.setIdCardNumber(merchant.getIdCardNumber());
                        merchantIncreaseLimitMapper.updateMerchantIncreaseLimit(merchantIncreaseLimit);
                    }
                }
            }
        }
        return AjaxResult.successAndData("获取信用卡列表成功", list);
    }

    @Override
    public AjaxResult submitPlan(JSONObject jsonObject) {
        // TODO Auto-generated method stub
        // 获取小计划详情列表
        JSONArray list = jsonObject.getJSONArray("dataList");
        // 获取执行时间
        String dateStr = jsonObject.getString("dateStr");
        // 要还金额
        BigDecimal planMoney = jsonObject.getBigDecimal("planMoney");
        // 平台商户id
        String merid = jsonObject.getString("merId");
        // 平台商户名称
        String merchantName = jsonObject.getString("merchantName");
        // 平台商户名称
        String merchantPhone = jsonObject.getString("merchantPhone");
        // 预留金
        BigDecimal turnOver = jsonObject.getBigDecimal("turnOver");
        // 卡号A
        String cardNumberA = jsonObject.getString("cardNumberA");
        // 卡号B
        String cardNumberB = jsonObject.getString("cardNumberB");
        // 计划类型
        Integer planType = jsonObject.getInteger("planType");
        // ip地址
        String ip = jsonObject.getString("ip");
        // 地区
        String region = jsonObject.getString("region");
        if (StringUtils.isEmpty(ip)) {
            return AjaxResult.error(1, "获取终端ip失败,请重新制定计划！如有疑问请联系客服!");
        }
        if (StringUtils.isEmpty(region)) {
            return AjaxResult.error(1, "请选择地区");
        }
        List<PlanNew> plA = planNewMapper.selectBadDebt(cardNumberA);
        List<PlanNew> plB = planNewMapper.selectBadDebt(cardNumberB);
        if (plA.size() > 0) {
            return AjaxResult.error(cardNumberA + "卡已存在计划，请勿重复制定");
        }
        if (plB.size() > 0) {
            return AjaxResult.error(cardNumberB + "卡已存在计划，请勿重复制定");
        }
        PlanNew p = new PlanNew();
        String planId = StringUtils.randomUUID();
        p.setId(planId);
        // 商户id
        p.setMerchantId(merid);
        p.setMerchantName(merchantName);
        p.setMerchantPhone(merchantPhone);
        p.setStatus(0);// 状态待执行
        // 创建时间
        p.setCreateTime(new Date());
        // 要还金额
        p.setPlanAmt(planMoney);
        // 预留金
        p.setCbAmt(turnOver);
        // 计划类型1智能还2异卡还
        p.setType(planType);
        // 还款笔数
        p.setEveryNum(jsonObject.getInteger("everyNum"));
        // 执行时间
        p.setExecutionTime(dateStr);
        // 最大组数
        p.setMaxGroupNum(jsonObject.getInteger("maxGroupNum"));
        p.setRegion(region);
        p.setRate(jsonObject.getString("rate"));
        p.setCardNumberA(cardNumberA);
        p.setCardNumberB(cardNumberB);
        p.setPro(jsonObject.getString("pro"));
        for (int i = 0; i < list.size(); i++) {
            JSONObject planitems = list.getJSONObject(i);
            PlanItemNew planItem = new PlanItemNew();
            // id
            planItem.setId(StringUtils.randomUUID());
            // 大计划id
            planItem.setPlanId(p.getId());
            // 信用卡id
            planItem.setCardId(planitems.getString("cardId"));
            // 卡号
            planItem.setCardNumber(planitems.getString("cardNum"));
            // 银行名称
            planItem.setCardName(planitems.getString("cardName"));
            // 金额
            planItem.setMoney(planitems.getBigDecimal("money"));
            // 待执行
            planItem.setStatus(0);
            // 执行时间
            planItem.setPlanTime(planitems.getDate("time"));
            // 金额类型
            planItem.setMoneyType(planitems.getString("type"));
            // 组数
            planItem.setGroupNumber(planitems.getInteger("groupNum"));
            // 地区
            planItem.setRegion(region);
            // 通道id
            planItem.setAcqId(planitems.getString("acqId"));
            // 通道Code
            planItem.setAcqCode(planitems.getString("acqCode"));
            // 设备名称
            planItem.setDeviceCode(jsonObject.getString("deviceCode"));
            // ip地址
            planItem.setIp(ip);
            planItemNewMapper.insertPlanItemNew(planItem);
        }
        planNewMapper.insertPlanNew(p);
        return AjaxResult.successAndData("提交计划成功", planId);
    }

    @Override
    public AjaxResult updatePlanStatusById(PlanNew planNew) {
        if (planNew == null) {
            return AjaxResult.error("修改计划失败，缺失参数！");
        }
        try {
            if (planNewMapper.updatePlanNew(planNew) > 0) {
                return AjaxResult.success("更改计划成功！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("app更改计划失败=" + e.toString());
            return AjaxResult.error("更改计划失败，请联系客服咨询！");
        }
        return AjaxResult.error("更改计划失败，请联系客服咨询！");
    }

}
